class DrawGraph {
    constructor({
        borderDis = Number(($('#themetic-canvas').offsetWidth - $('.img_box').offsetWidth) / 2),
        contentName = 'contentId',
        allColor,
        beginColor,
    }) {
        let svgW = $(`#${contentName}`).width() - 4 * borderDis;
        let svgH = $(`#${contentName}`).height() - 2 * borderDis;
        let arrorStr = '';
        for (let i = 0; i < allColor.length; i++) {
            arrorStr +=
                '<defs><marker id="markerArrow' +
                i +
                '" markerWidth="8" markerHeight="8" refx="2" refy="5" orient="auto">' +
                '<path class="arrowColorCtrl"  d="M2,2 L2,8 L8,5 L2,2" style = "fill: ' +
                allColor[i] +
                '" /> </marker> </defs>';
        }
        // 初始化svg
        let svgStr =
            '<svg id="svgBox" width="' +
            svgW +
            'px"  height="' +
            svgH +
            'px" xmlns="http://www.w3.org/2000/svg" version="1.1">' +
            arrorStr +
            '</svg > ';
        $(`#${contentName}`).append(svgStr);
        // 初始化fontDom
        let dom = document.createElement('div');
        dom.className = 'draw_fontBox';
        dom.id = 'drawFont';
        $(`#${contentName}`).append(dom);

        // 所有绘制的图标
        this.allSign = [];
        // 开始点
        this.beginPoint = [];
        // 多面所有的点位
        this.polyginAllPoint = [];
        // 视口容器
        this.contentBox = document.getElementById(contentName);
        // 图片和canvas间距
        this.borderDis = borderDis;
        // 选择绘制的类型
        this.type = null;
        // 颜色选择
        this.graphColor = beginColor;
        // 颜色的数组下表
        this.colorIndex = allColor.findIndex(item => item === beginColor);
        // 初始字体框的宽度
        this.inputFontWidth = 20;
        // 初始字体框的高度
        this.inputFontHeight = 30;
        // 文字字号
        this.fontSize = '16px';
        // 文字颜色
        this.fontColor = beginColor;
        // 文字是否加粗
        this.fontIsWeight = false;
        // 临时svg
        this.temporarySvg = null;
        setTimeout(() => {
            // svg的容器
            this.svgBox = document.getElementById('svgBox');
            this.fontBox = document.getElementById('drawFont');
            this.addLisToSvg();
        }, 0);
    }
    changeType(type) {
        type === 'font'
            ? $('.draw_fontBox').css('pointer-events', 'auto')
            : $('.draw_fontBox').css('pointer-events', 'none');
        this.type = type;
    }
    changeColor(val, colorIndex) {
        this.graphColor = val;
        this.fontColor = val;
        this.colorIndex = colorIndex;
    }
    showOrHide(flag) {
        if (flag) {
            $('#svgBox').show();
        } else {
            $('#svgBox').hide();
        }
    }
    // svg监听
    addLisToSvg() {
        // 文本图层双击监听
        this.fontBox.addEventListener('dblclick', env => {
            if (env.target.className !== 'draw_fontClass' && this.type && this.type === 'font') {
                let dom = this.addFontBox([env.layerX, env.layerY]);
                $('.draw_fontBox').append(dom);
                setTimeout(() => {
                    dom.focus();
                });
            }
        });
        // 绘制图层点击监听
        this.svgBox.addEventListener('click', env => {
            if (this.type && this.type !== 'font') {
                if (this.beginPoint.length > 0) {
                    // 如果是多面，单击只是添加转折点
                    if (this.type === 'polygon') {
                        this.drawCurrentSvg(this.beginPoint, [env.layerX, env.layerY], this.type);
                    } else {
                        let sign = this.drawCurrentSvg(
                            this.beginPoint,
                            [env.layerX, env.layerY],
                            this.type
                        );
                        this.allSign.push(sign);
                        this.svgBox.appendChild(sign);
                        this.beginPoint = [];
                        $('.temporarySvg').remove();
                        this.temporarySvg = null;
                    }
                } else {
                    this.beginPoint = [env.layerX, env.layerY];
                }
            }
        });
        // 绘制图层移动监听
        this.svgBox.addEventListener('mousemove', env => {
            if (this.type) {
                if (this.beginPoint.length > 0) {
                    if (this.temporarySvg) {
                        this.changeCurrentSvg(this.beginPoint, [env.layerX, env.layerY], this.type);
                    } else {
                        this.svgBox.appendChild(
                            this.drawCurrentSvg(
                                this.beginPoint,
                                [env.layerX, env.layerY],
                                this.type,
                                true
                            )
                        );
                    }
                }
            }
        });
        // 绘制图层双击监听
        this.svgBox.addEventListener('dblclick', env => {
            if (this.type && this.type === 'polygon') {
                if (this.beginPoint.length > 0) {
                    let sign = this.drawCurrentSvg(
                        this.beginPoint,
                        [env.layerX, env.layerY],
                        this.type,
                        null,
                        true
                    );
                    this.allSign.push(sign);
                    this.svgBox.appendChild(sign);
                    this.beginPoint = [];
                    this.polyginAllPoint = [];
                    $('.temporarySvg').remove();
                    this.temporarySvg = null;
                }
            }
        });
    }
    // 添加文字框
    addFontBox(beginArr, isTemporary) {
        let dom = document.createElement('div');
        dom.className = 'draw_fontClass';
        dom.setAttribute('contenteditable', true);
        dom.setAttribute('tabindex', '0');

        let inputMinWidth = this.inputFontWidth;
        let inputHeight = this.inputFontHeight;

        let maxWidth = $('.draw_fontBox').width() - beginArr[0] + inputMinWidth / 2;
        let maxHeight = $('.draw_fontBox').height() - beginArr[1] + inputHeight / 2;
        // 总共添加几行文字
        let lineNum = Math.floor(maxHeight / Number(this.fontSize.replace('px', ''))) - 2;
        dom.setAttribute(
            'style',
            `position:absolute;
            left:${beginArr[0] - inputMinWidth / 2}px;
              top: ${beginArr[1] - inputHeight / 2}px;
              color:${this.fontColor};
                min-width:${inputMinWidth}px;
                max-width:${maxWidth}px;
                min-height:${inputHeight}px;
                font-size:${this.fontSize};
                -webkit-line-clamp: ${lineNum};`
        );
        return dom;
    }
    // 绘制svg
    /**
     *
     * @param {*} beginArr :起点
     * @param {*} endArr ：终点
     * @param {*} type ：类型
     * @param {*} isTemporary：是否为已经有临时点的dom
     * @param {*} isPolygonEnd ：是否是绘制面终结的触发
     * @returns
     */
    drawCurrentSvg(beginArr, endArr, type, isTemporary, isPolygonEnd) {
        let dom = null;
        let arrowSvgDom = null;
        let maxX = null;
        let minX = null;
        let maxY = null;
        let minY = null;
        let disR = null;
        switch (type) {
            case 'arrow':
                // 修改箭头颜色
                // $('.arrowColorCtrl').attr('style', `fill: ${this.graphColor}`);
                arrowSvgDom = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                arrowSvgDom.setAttribute(
                    'd',
                    `M${beginArr[0]},${beginArr[1]} L${endArr[0]},${endArr[1]}`
                );
                arrowSvgDom.setAttribute('style', `fill: ${this.graphColor}`);
                arrowSvgDom.setAttribute('stroke', this.graphColor);
                arrowSvgDom.setAttribute('stroke-width', '2');
                arrowSvgDom.setAttribute('marker-end', 'url(#markerArrow' + this.colorIndex + ')');
                dom = arrowSvgDom;
                break;

            case 'rect':
                arrowSvgDom = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
                maxX = Math.max(beginArr[0], endArr[0]);
                minX = Math.min(beginArr[0], endArr[0]);
                maxY = Math.max(beginArr[1], endArr[1]);
                minY = Math.min(beginArr[1], endArr[1]);
                arrowSvgDom.setAttribute('x', minX);
                arrowSvgDom.setAttribute('y', minY);
                arrowSvgDom.setAttribute('width', maxX - minX);
                arrowSvgDom.setAttribute('height', maxY - minY);

                arrowSvgDom.setAttribute('stroke', this.graphColor);
                arrowSvgDom.setAttribute('stroke-width', '2');
                arrowSvgDom.setAttribute('style', `fill: rgba(255,255,255,0)`);
                dom = arrowSvgDom;
                break;

            case 'circle':
                arrowSvgDom = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
                disR = Math.sqrt(
                    Math.pow(beginArr[0] - endArr[0], 2) + Math.pow(beginArr[1] - endArr[1], 2)
                );
                arrowSvgDom.setAttribute('cx', `${beginArr[0]}`);
                arrowSvgDom.setAttribute('cy', `${beginArr[1]}`);
                arrowSvgDom.setAttribute('r', `${disR}`);

                arrowSvgDom.setAttribute('fill', `rgba(255,255,255,0)`);
                arrowSvgDom.setAttribute('stroke', this.graphColor);
                arrowSvgDom.setAttribute('stroke-width', '2');
                dom = arrowSvgDom;
                break;
            case 'polygon':
                if (this.temporarySvg && !isPolygonEnd) {
                    this.polyginAllPoint.push(...endArr);
                    this.temporarySvg.setAttribute('points', this.polyginAllPoint);
                    arrowSvgDom = Object.assign({}, this.temporarySvg);
                } else {
                    this.polyginAllPoint.push(...endArr);
                    arrowSvgDom = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
                    arrowSvgDom.setAttribute('points', this.polyginAllPoint);
                    arrowSvgDom.setAttribute('stroke', this.graphColor);
                    arrowSvgDom.setAttribute('stroke-width', '2');
                    arrowSvgDom.setAttribute('style', `fill: rgba(255,255,255,0.5)`);
                }
                dom = arrowSvgDom;
                break;
            default:
                dom = document.createElement('div');
                break;
        }
        if (isTemporary) {
            dom.className.baseVal = 'temporarySvg';
            this.temporarySvg = dom;
        }
        return dom;
    }
    // 临时svg修改属性
    changeCurrentSvg(beginArr, endArr, type) {
        console.log('move');
        let dom = null;
        let maxX = null;
        let minX = null;
        let maxY = null;
        let minY = null;
        let disR = null;
        let temPoints = null;
        switch (type) {
            case 'arrow':
                this.temporarySvg.setAttribute(
                    'd',
                    `M${beginArr[0]},${beginArr[1]} L${endArr[0]},${endArr[1]}`
                );
                break;
            case 'rect':
                maxX = Math.max(beginArr[0], endArr[0]);
                minX = Math.min(beginArr[0], endArr[0]);
                maxY = Math.max(beginArr[1], endArr[1]);
                minY = Math.min(beginArr[1], endArr[1]);
                this.temporarySvg.setAttribute('x', minX);
                this.temporarySvg.setAttribute('y', minY);
                this.temporarySvg.setAttribute('width', maxX - minX);
                this.temporarySvg.setAttribute('height', maxY - minY);
                break;
            case 'circle':
                disR = Math.sqrt(
                    Math.pow(beginArr[0] - endArr[0], 2) + Math.pow(beginArr[1] - endArr[1], 2)
                );
                this.temporarySvg.setAttribute('cx', `${beginArr[0]}`);
                this.temporarySvg.setAttribute('cy', `${beginArr[1]}`);
                this.temporarySvg.setAttribute('r', `${disR}`);
                break;
            case 'polygon':
                temPoints = this.polyginAllPoint.concat(endArr);
                this.temporarySvg.setAttribute('points', temPoints);
                break;
            default:
                dom = document.createElement('div');
                break;
        }
        return dom;
    }
    // 清空所有标绘
    clearDraw() {
        this.allSign.forEach(item => {
            item.remove();
        });
        // $(this.svgBox).empty();
        $(this.fontBox).empty();
    }
}

export default DrawGraph;
